package com.zhiyou100.dao.Impl;

import com.zhiyou100.JDBCUtil.DBUtil;
import com.zhiyou100.dao.RoleDao;
import com.zhiyou100.emtity.Role;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: 马跃
 * @create: 2021-01-20 17:32
 **/
public class RoleDaoImpl implements RoleDao {

    private QueryRunner qur = new QueryRunner(DBUtil.getDataSource());
    @Override
    public List<Role> queryAll() {
        String sql="select * from role";
        List<Role> list = null;
        try {
            list = qur.query(sql, new BeanListHandler<>(Role.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    @Override
    public void add(Role role) {
        String sql = "insert into role(r_id,r_name,r_des,r_addTime) values (null,?,?,?)";
        try {
            qur.update(sql,role.getR_name(),role.getR_des(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return;
    }

    @Override
    public void delete(int id) {
        String sql = "delete from role where r_id = ?";
        try {
            qur.update(sql,id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return;
    }

    @Override
    public Role query(int id) {
        String sql="select * from role where r_id=?";
        try {
            Role query = qur.query(sql, new BeanHandler<>(Role.class), id);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(Role role) {
        String sql = "update role set r_name=?,r_des=?,r_addTime=? where r_id=?";
        try {
            qur.update(sql, role.getR_name(),role.getR_des(),role.getR_addTime(),role.getR_id());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return;
    }

    @Override
    public List<Role> likeQuery(String like) {
        String sql = "select * from role where r_name like ?";
        String a = "%"+like+"%";
        try {
            List<Role> query = qur.query(sql, new BeanListHandler<>(Role.class), a);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

}
